package j2024.j202407;

import java.util.ArrayList;
import java.util.List;

public class j0728 {
    /**46. 全排列
     *
     */
    List<List<Integer>> ret;
    List<Integer> path;
    boolean[] check;
    public List<List<Integer>> permute1(int[] nums) {
        ret = new ArrayList<>();
        path = new ArrayList<>();
        check = new boolean[nums.length];
        dfs1(nums);
        return ret;
    }
    public void dfs1(int[] nums){
        if(nums.length==path.size()){
            ret.add(new ArrayList<>(path));
            return;
        }
        for (int i = 0; i < nums.length; i++) {
            if(check[i]==false){
                path.add(nums[i]);
                check[i] = true;
                dfs1(nums);
                //恢复现场
                check[i] = false;
                path.remove(path.size()-1);
            }
        }
    }
    public List<List<Integer>> permute(int[] nums) {
        ret = new ArrayList<>();
        path = new ArrayList<>();
        check = new boolean[nums.length];
        dfs(nums);
        return ret;
    }
    public void dfs(int[] nums){
        if(path.size() == nums.length){
            ret.add(new ArrayList<>(path));
            return;
        }
        for (int i = 0; i < nums.length; i++) {
            if(check[i]==false){
                path.add(nums[i]);
                check[i] = true;
                dfs(nums);
                //回溯 恢复
                check[i] = false;
                path.remove(path.size()-1);
            }
        }
    }

    /**
     * 78. 子集
     * @param nums
     * @return
     */
    public List<List<Integer>> subsets(int[] nums) {
        ret = new ArrayList<>();
        path = new ArrayList<>();
        Dfs(nums,0);
        return ret;
    }
    public void Dfs(int[] nums,int i){
        if(i==nums.length){
            ret.add(new ArrayList<>(path));
            return;
        }
        //选
        path.add(nums[i]);
        Dfs(nums,i+1);
        path.remove(path.size()-1);
        //不选
        Dfs(nums,i+1);
    }
    public void Dfs2(int[] nums,int i){
        ret.add(new ArrayList<>(path));
        for(int j = i;j < nums.length;j++){
            path.add(nums[j]);
            Dfs2(nums,j+1);
            path.remove(path.size()-1);
        }
    }
}
